package com.atguigu.datastream.day05;

import com.atguigu.datastream.bean.Event;
import com.atguigu.datastream.test.day03.Flink_05_Source_useDefault;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.HashSet;

/**
 * ClassName: Flink06_ProcessTimeWindow_WindowFun
 * Package: com.atguigu.day05
 * Description:
 *         使用全窗口函数applyWindowFun实现UV的计算
 * @Author ChenJun
 * @Create 2023/4/11 18:17
 * @Version 1.0
 */
public class Flink06_ProcessTimeWindow_WindowFun {
    public static void main(String[] args) throws Exception {

        //1. 创建流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.通过自定义数据源获取数据
        DataStreamSource<Event> streamSource = env.addSource(new Flink_05_Source_useDefault.ClickSource());

        //3. 将相同的key放到同一个分区
        KeyedStream<Event, String> keyedStream = streamSource.keyBy(new KeySelector<Event, String>() {
            @Override
            public String getKey(Event event) throws Exception {
                return "key";
            }
        });

        //4.开启一个基于处理时间的滚动窗口，每五秒计算一次5秒内的UV
        WindowedStream<Event, String, TimeWindow> window = keyedStream.window(TumblingProcessingTimeWindows.of(Time.seconds(5)));

        //TODO 5.使用全窗口函数ProcessWindowFun实现UV的计算


        window.apply(new WindowFunction<Event, Integer, String, TimeWindow>() {
            @Override
            public void apply(String s, TimeWindow timeWindow, Iterable<Event> iterable, Collector<Integer> collector) throws Exception {
                HashSet<String> set = new HashSet<>();
                for (Event event : iterable) {
                    set.add(event.user);
                }

                collector.collect(set.size());
            }
        }).print();


        env.execute();

    }
}
